package com.example.license.service;

import com.example.license.Util;
import com.example.license.dao.LicenseRepository;
import com.example.model.License;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;


@Service
public class LicenseService {
    @Autowired
    private LicenseRepository licenseRepository;

    public License getLicenseById(int id){
        return licenseRepository.findById(id).orElse(null);
    }

    @HystrixCommand(
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),
                    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000"),
                    @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000")
            },
            fallbackMethod = "builderFallbackLicenseList",
            threadPoolKey = "licenseRepository",
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize", value = "10"),
                    @HystrixProperty(name = "maxQueueSize", value = "-1")
            }
    )
    public Iterable<License> getAllLicense(){
        Util.randomSleep();
        return licenseRepository.findAll();
    }

    private Iterable<License> builderFallbackLicenseList(){
        License license = new License();
        license.setId(-1);
        license.setName("fallbackLicense");
        license.setOrgId(-1);
        return Arrays.asList(license);
    }
}
